#include "normalise.h"

using namespace std;

template<class T> class Image
{
private:
    IplImage* imgp;
public:
    Image(IplImage* img=0)
    {
        imgp=img;
    }
    ~Image()
    {
        imgp=0;
    }
    void operator=(IplImage* img)
    {
        imgp=img;
    }
    inline T* operator[](const int rowIndx)
    {
        return ((T *)(imgp->imageData + rowIndx*imgp->widthStep));
    }
};

typedef struct
{
    unsigned char b,g,r;
} RgbPixel;

typedef struct
{
    float b,g,r;
} RgbPixelFloat;

typedef Image<RgbPixel>       RgbImage;
typedef Image<RgbPixelFloat>  RgbImageFloat;
typedef Image<unsigned char>  BwImage;
typedef Image<float>          BwImageFloat;

// normalisation d'histogramme
void normalise(IplImage* img)
{
    BwImage _img(img);
    int w=img->width;
    int h=img->height;

    int histo[256] = {0};

    for(int x=0; x<w; x++)
    {
        for(int y=0; y<h; y++)
        {
            histo[_img[x][y]]++;
        }
    }

    int map[256];
    int cumul=0;

    for(int i=0 ; i<256 ; i++)
    {
        map[i]=(255*cumul)/(h*w);
        cumul+=histo[i];
    }

    for(int x=0; x<w; x++)
    {
        for(int y=0; y<h; y++)
        {
            _img[x][y]=map[ _img[x][y] ];
        }
    }
}

void normalize(IplImage*& img, int normWidth, int normHeight)
{
	IplImage* dst = NULL;

	// Mise en niveau de gris et redimentionnement
	dst = cvCreateImage(cvSize(normWidth, normHeight), img->depth,  img->nChannels);
    cvResize(img, dst);

    // Normalisation de l'image
    //normalise(dst);

    cvReleaseImage(&img);
    img = dst;
}
